package com.sclibackup.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.sclibackup.common.DataSourceChange;
import com.sclibackup.common.DynamicDataSource;

@Aspect  
@Component
public class DataSourceAspect {

	@Around("@annotation(dataSourceChange)") 
	public Object doAround(ProceedingJoinPoint pjp, DataSourceChange dataSourceChange){
		Object retVal = null;  
        boolean selectedDataSource = false; 
        try {  
            if (null != dataSourceChange) {  
                selectedDataSource = true;  
                if (dataSourceChange.slave()) {  
                    DynamicDataSource.useSlave();  
                } else {  
                    DynamicDataSource.useMaster();  
                }  
            }  
            retVal = pjp.proceed();  
        } catch (Throwable e) {  
            e.printStackTrace(); 
        } finally {  
            if (selectedDataSource) {  
                DynamicDataSource.reset();  
            }  
        }  
        return retVal;
	}
}
